package com.ptswitch.material.pages.material;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.hxzon.project.AppRuntimeException;
import org.slf4j.Logger;
import org.springframework.dao.DataAccessException;

import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.model.material.MaterialOrigFile;
import com.ptswitch.material.pages.base.MaterialBasePage;
import com.ptswitch.material.service.MaterialExcelService;
import com.ptswitch.material.service.MaterialService;
import com.ptswitch.material.util.HlogConstants;

public class ImportMaterial extends MaterialBasePage {
    public static int importType_none = 1;
    public static int importType_new = 2;
    public static int importType_all = 3;
    @Inject
    private Logger logger;
    @Inject
    private MaterialService materialSer;
    @Inject
    private MaterialExcelService excelSer;
    @Property
    private UploadedFile file;
    @Property
    private int importType = importType_none;
    @Property
    // @Persist
    private List<Material> dbMaterials = new ArrayList<Material>();
    @Property
    // @Persist
    private List<Material> updateMaterials = new ArrayList<Material>();
    @Property
    private List<Material> newMaterials = new ArrayList<Material>();
    @Property
    private List<Material> notUniqueList = new ArrayList<Material>();
    @InjectPage
    private ListMaterial listMaterial;

    @OnEvent(value = EventConstants.SUCCESS)
    public Object importMaterial() {
        checkUserIsAdmins();
        List<Material> materials = new ArrayList<Material>();
        MaterialOrigFile upload = getWebUtil().upload(file, MaterialOrigFile.class);
        try {
            excelSer.buildMaterialsFromExcel(materials, getWebUtil().getRealFilePath(upload));
        } catch (Exception e) {
            getWebUtil().delete(upload);
            throw AppRuntimeException.rethrow("读取物料表文件错误", e);
        }
        // unique check
        Map<String, Material> map = new HashMap<String, Material>();
        Set<String> materialCodeList = new HashSet<String>();
        notUniqueList.clear();
        for (Material material : materials) {
            if (map.containsKey(material.getCode())) {
                materialCodeList.add(material.getCode());
                notUniqueList.add(material);
            } else {
                map.put(material.getCode(), material);
            }
        }
        for (String code : materialCodeList) {
            notUniqueList.add(map.get(code));
        }
        if (!notUniqueList.isEmpty()) {
            Collections.sort(notUniqueList);
            getWebUtil().delete(upload);
            throw AppRuntimeException.error("导入物料表错误：物料表中含有以下重复数据");
        }
        // db check
        dbMaterials.clear();
        updateMaterials.clear();
        newMaterials.clear();
        Material dbMaterial;
        for (Material material : materials) {
            //FIXME
            dbMaterial = materialSer.findByCode(material.getCode());
            if (dbMaterial != null) {
                dbMaterials.add(dbMaterial);
                updateMaterials.add(material);
            } else {
                newMaterials.add(material);
            }
        }
        // importType
        try {
            if (importType == importType_all) {
                materialSer.saveAll(newMaterials);
                materialSer.deleteAll(dbMaterials);
                materialSer.saveAll(updateMaterials);
                String log = HlogConstants.addListMaterial + newMaterials.size() + "个," + HlogConstants.updateListMaterial + updateMaterials.size() + "个";
                logger.info(log);
                hlog(log);
            } else if (importType == importType_new) {
                materialSer.saveAll(newMaterials);
                String log = HlogConstants.addListMaterial + newMaterials.size() + "个";
                logger.info(log);
                hlog(log);
            } else if (importType == importType_none) {
                if (dbMaterials.isEmpty()) {
                    materialSer.saveAll(newMaterials);
                    String log = HlogConstants.addListMaterial + newMaterials.size() + "个";
                    logger.info(log);
                    hlog(log);
                } else {
                    getWebUtil().delete(upload);
                    throw AppRuntimeException.error("导入物料表错误：物料表中含有已存档的物料");
                }
            }
        } catch (Throwable e) {
            if (e instanceof DataAccessException) {
                e = e.getCause().getCause();
            }
            throw AppRuntimeException.rethrow("导入物料表错误", e);
        }
        // display
        return listMaterial;
        // return null;
    }

}
